<template>
  <div class="Login">
    <shop-header> 登录 </shop-header>
    <logo></logo>
    <van-field
      v-model="usename"
      label="用户名"
      clearable
      :error-message="errorUsenameMes"
      @input="checkUsename"
    />
    <van-field
      v-model="password"
      type="password"
      label="密码"
      clearable
      :error-message="errorPasswordMes"
      @input="checkPassword"
    />
    <shop-button @click.native="checkInformation">登录</shop-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      usename: "",
      password: "",
      errorPasswordMes: "",
      errorUsenameMes: "",
    };
  },
  created() {
    console.log(this.$route);
    const { usename, password } = this.$route.params;
    if (usename != "" && password != "") {
      this.usename = usename;
      this.password = password;
    }
  },
  methods: {
    async checkInformation() {
      if (
        this.usename !== "" &&
        this.password !== "" &&
        this.errorPasswordMes == "" &&
        this.errorUsenameMes == ""
      ) {
        const res = await this.$axios.post("/login", {
          username: this.usename,
          password: this.password,
        });
        console.log(res);
        const { message, statusCode, data } = res.data;
        if (statusCode === 200) {
          this.$toast(message);
          localStorage.setItem("token", data.token);
          localStorage.setItem("id", data.user.id);
          this.$router.push("/user");
        } else {
          this.$toast(message);
        }
      } else {
        this.$toast("密码或用户名格式不正确");
      }
    },
    checkUsename() {
      if (this.usename == "") {
        this.errorUsenameMes = "";
      } else {
        const reg = /^1\d{3,5}$/;
        if (reg.test(this.usename)) {
          this.errorUsenameMes = "";
        } else {
          this.errorUsenameMes = "用户名的格式错误";
        }
      }
    },
    checkPassword() {
      if (this.password == "") {
        this.errorPasswordMes = "";
      } else {
        const reg = /^\d{3,12}$/;
        if (reg.test(this.password)) {
          this.errorPasswordMes = "";
        } else {
          this.errorPasswordMes = "密码格式不正确";
        }
      }
    },
  },
};
</script>

<style></style>
